import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import VueCookies from 'vue-cookies'
import api from '../api/api'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('../views/AboutView.vue'),
      meta: {
        login: true
      }
    },
    {
      path: '/test',
      name: 'test',
      component: () => import('../views/TestView.vue')
    },
    {
      path: '/login',
      name: "login",
      title: "登录页",
      component: () => import('../views/LoginView.vue'),
      meta: {
        login: true
      }
    },
    {
      path: '/giteeLogin',
      name: 'giteeLogin',
      title: "oauth2登录",
      component: () => import('../views/GiteeView.vue')
    },
    {
      path: '/loginGiteeSuccess',
      name: 'giteeLoginSuccess',
      title: "oauth2登录成功",
      component: () => import('../views/GiteeLoginSuccessView.vue'),
    },
    {
      path: '/product',
      name: 'product',
      title: '饺子选择界面',
      component: () => import('../views/ProductView.vue'),
      meta: {
        login: true
      }
    },
    {
      path: '/loginExpired',
      name: 'loginExpired',
      title: '登录过期界面',
      component: () => import('../views/LoginExpiredView.vue'),
      meta: {
        login: true
      }
    }
  ]
})

async function getUpdateLoginState() {
  const res = await api.loginStateUpdate();
  return res
}
//路由守卫
router.beforeEach(async (to, from, next) => {
  /*
      有些路由是需要登录的，判断登录状态
          1.没有登录：跳转到登录页
          2.登录：直接进入
      有些路由是不需要登录的，直接进入
      ps：是否需要登录 --meta
  */
  const token = localStorage.getItem('token');
  const isLogin = !!token;
  const updateTime = VueCookies.get('updateTime');

  // 更新用户的登陆状态
  if (!updateTime && isLogin) {
    console.log("正在更新用户登录状态信息");
    VueCookies.set('updateTime', "used", "1h");
    var state = await getUpdateLoginState();
    if (state != true) {
      console.log("需要去除当前token")
      next('/loginExpired');
      return;
    } else {
      console.log("更新状态成功")
    }
  }


    if (to.matched.some(item => item.meta.login)) {//需要登录
      console.log("需要登录");
      if (isLogin) {//已经登录的，判断是否需要更新用户登录状态信息
        next();
        return;
      }
      if (!isLogin && to.name === 'giteeLogin') {//未登录，但是要去登录页
        next();
      }
      if (!isLogin && to.name !== 'giteeLogin') {//未登录，去的也是登录页
        next({ name: 'giteeLogin' });
      }
    } else {
      next();
    }
  })




export default router
